package com.mooc.ppjoke;

import android.util.Log;

import androidx.room.Room;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bw.baseapplication_sdk.BaseApplication;
import com.bw.common.entity.RoomUserEntity;
import com.bw.common.eventbus.EventBusEntity;
import com.bw.common.mvvm.viewmodel.BaseViewModel;
import com.bw.network_sdk.entity.BaseEntity;
import com.mooc.ppjoke.entity.IsLoginEntity;
import com.mooc.ppjoke.entity.LoginEntity;
import com.mooc.ppjoke.loginroom.LoginDataBase;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginViewModel extends BaseViewModel<LoginModel> {

    public void addLoginRoom(RoomUserEntity roomUserEntity){
        LoginDataBase build = Room.databaseBuilder(BaseApplication.getInstance(), LoginDataBase.class, "login.db").build();
        mModel.addLogin(build.getLoginDao(),roomUserEntity.data.data)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    public void addInsertUser(LoginEntity loginEntity){
        mModel.requestUserEntity(loginEntity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }



    @Override
    protected void initData() {
    }

    @Override
    protected void onRestle(BaseEntity entity) {
        if (entity instanceof IsLoginEntity){
            IsLoginEntity isLoginEntity = (IsLoginEntity) entity;
            LogUtils.e(isLoginEntity.message);
            SPUtils.getInstance().put("isLogin",true);
        }else if (entity instanceof RoomUserEntity){
            RoomUserEntity roomUserEntity = (RoomUserEntity) entity;
            addLoginRoom(roomUserEntity);
            EventBusEntity eventBusEntity = new EventBusEntity();
            eventBusEntity.action = "refresh";
            Map<String,Object> map = new HashMap<>();
            map.put("RoomEntity",roomUserEntity);
            eventBusEntity.data =map;
            EventBus.getDefault().post(eventBusEntity);
        }
    }
}
